﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using System.Runtime.Serialization;
using DataFlock.CRM.Engine.SDK;
using DataFlock.CRM.Engine.Common;

namespace DataFlock.CRM.Engine
{
    public class BusinessEntity<T> : BaseBusinessEntity<T>
    {
        private EntityMetadata _metadata;

        public BusinessEntity()
        {
            LogicalName = Metadata.LogicalName;
        }

        public BusinessEntity(Guid entityId)
        {
            EntityId = entityId;
        }

        public EntityMetadata Metadata
        {
            get
            {
                if (_metadata == null)
                {
                    RetrieveEntityRequest req = new RetrieveEntityRequest()
                    {
                        LogicalName = typeof(T).Name.ToLowerInvariant(),
                        EntityFilters = EntityFilters.All
                    };

                    RetrieveEntityResponse resp = CRMHelper.GetService().Execute(req) as RetrieveEntityResponse;
                    _metadata = resp.EntityMetadata;
                }

                return _metadata;
            }
        }
    }
}
